<?php
/**
 * @author heimuya
 * Date 2014-02-07
 * 数据接口类
 */
class DataapiAction extends Action {
	protected $postdata = array();
	
	/**
	 * 构造函数
	 */
	 public function _initialize(){
	 	$this->postdata = $this->_request();
		unset($this->postdata['_URL_']);
	 }
	 
	/**
	 * 签名
	 */
	 private function sign(){
	 	$signed = $this->postdata['sign'];
		unset($this->postdata['sign']);
		$sign = '';
		foreach ($this->postdata as $key => $value) {
			$sign .= $key.$value;
		}
		if(strtolower($signed) !== strtolower(md5($sign))) return FALSE;//验证sign
		return TRUE;
	 }
	 
	/**
	 * 验证软件新版本
	 */
	 public function checkupdate(){
	 	$oldversion = $this->_request('version');
		
		$filename = SYSTEM_ROOT_PATH.'client/version.txt';
		if(!file_exists($filename)){
			if(!is_writeable(SYSTEM_ROOT_PATH.'client/')) {
		        echo json_encode(array('status' => FALSE, 'url' => '', 'md5' => ''));
		        exit(0);
		    }
			touch($filename);
		}
		$version = trim(file_get_contents($filename));//原始版本号
		if($version !== $oldversion){
			$newversion = SYSTEM_ROOT_PATH.'client/version'.$version.'.msi';
			echo json_encode(array('status' => TRUE, 'url' => $_SERVER['SERVER_NAME'].'/hjjp/client/version'.$version.'.msi', 'md5' => md5_file($newversion)));
		    exit(0);
		}else{
			echo json_encode(array('status' => FALSE, 'url' => '', 'md5' => ''));
		    exit(0);
		}
	 }
	 
	/**
	 * 机台注册
	 */
	 public function register(){
	 	if(!$this->sign()) {
			echo json_encode(array('status' => FALSE, 'code' => -1));
			exit(0);
		}
	 	$where['number'] = $this->postdata['number'];
		$machine = D('Machine')->field('id, uid, number')->where($where)->find();
		
		if(!$machine){
			echo json_encode(array('status' => FALSE, 'code' => 1));
			exit(0);
		}
		
		//检测此机台是否被注册
		$where1['uid'] = $this->postdata['uid'];
		$machineinfo = D('MachineView')->where($where1)->find();
		if($machineinfo){
			if($machineinfo['mnumber'] != $this->postdata['number']){
				echo json_encode(array('status' => FALSE, 'code' => 1));
				exit(0);
			}else{
				$connday = M('System')->field('value')->where(array('name' => 'connectday'))->find();
				echo json_encode(array('status' => TRUE, 'code' => 0, 'snumber' => $machineinfo['sname'], 'mnumber' => $machineinfo['mnumber'], 'connectday' => intval($connday['value'])));
				exit(0);
			}
		}
		
		if($machine['uid'] != '' && $machine['uid'] != $this->postdata['uid']){
			echo json_encode(array('status' => FALSE, 'code' => 1));
			exit(0);
		}
		
		$data['uid'] = $this->postdata['uid'];
		$where = array('id' => $machine['id']);
		D('Machine')->where($where)->save($data);
		
		$machineinfo = D('MachineView')->where($where1)->find();
		$connday = M('System')->field('value')->where(array('name' => 'connectday'))->find();
		echo json_encode(array('status' => TRUE, 'code' => 0, 'snumber' => $machineinfo['sname'], 'mnumber' => $machineinfo['mnumber'], 'connectday' => intval($connday['value'])));
		exit(0);
	 }
	
	/**
	 * 验证用户名密码以及sign
	 * @return status查询状态  code结果代码
	 */
	 private function checkdata(){
		if(!$this->sign()) return array('status' => FALSE, 'code' => -1);//验证sign
		//验证机器与用户名密码
		$where['uid'] = $this->postdata['uid'];
		$machineinfo = D('MachineView')->where($where)->select();
		if(!$machineinfo){//机器未登记
			return array('status' => FALSE, 'code' => 1);
		}
		$user = array();
		$flag = FALSE;
		foreach ($machineinfo as $value) {
			if($value['nick'] == $this->postdata['user']){
				$flag = TRUE;
				$user = $value;
				break;
			}
		}
		if(!$flag){//用户不属于此机台
			return array('status' => FALSE, 'code' => 2);
		}
		if(strtolower($user['password']) !== strtolower($this->postdata['passwd'])){//用户密码错误
			return array('status' => FALSE, 'code' => 3);
		}
		//是否为有效用户
		if($user['valid'] !== 'y'){//用户被锁定，无法登陆，请联系管理员解锁
			return array('status' => FALSE, 'code' => 4);
		}
		else{//正常登陆
			return array('status' => TRUE, 'code' => 0);
		}
	 }
	 
	/**
	 * 用户登录接口
	 * 返回Json格式： {status:true/false, code:0/1/2}
	 */
	 public function login(){
	 	$check = $this->checkdata();
		if($check['status'] === FALSE){//验证错误
			echo json_encode($check);
			exit(0);
		}
	 	$where['nick'] = $this->postdata['user'];
		$data = array(
			'last_ip' 		=> get_client_ip(),
			'last_login'	=> time(),
			'status'		=> 'online'
		);
		D('User')->where($where)->save($data);
	 	$where1['uid'] = $this->postdata['uid'];
		$data = array(
			'updatetime'	=> time()
		);
		D('Machine')->where($where1)->save($data);
		echo json_encode($check);
		exit(0);
	 }
	 
	/**
	 * 查询菜单接口
	 * 返回Json格式：{"abstract": "axxxxxxxxxxx","category":[{"id": 2,"name": "黄家榜","sequence": 1}],"food": [{"id": 6,...}],"sauce":[{}],...}
	 */
	 public function foodmenu(){
	 	$check = $this->checkdata();
		if($check['status'] === FALSE){//验证错误
			echo json_encode(array('status' => FALSE, 'code' => 0));
			exit(0);
		}
		if(!($abstract = $this->checkabstract())){//无更新
			echo json_encode(array('abstract' => $this->postdata['abstract'], 'status' => 'No update'));
			exit(0);
		}
		$resp = array();
		$resp['abstract'] = $abstract;
		$resp['category'] = D("Category")->select();
		$resp['sauce'] = D("Sauce")->select();
		$resp['taste'] = D("Taste")->select();
		$resp['extra'] = D("Extra")->select();
		$resp['food'] = D('Food')->select();
		foreach ($resp['food'] as $key => $value) {
			$temp = json_decode($value['price']);
			$data = array();
			foreach ($temp as $tkey => $tvalue) {
				$data[] = array(
					'id'		=> intval($tkey),
					'price'		=> floatval($tvalue)
				);
			}
			$resp['food'][$key]['price'] = json_encode($data, JSON_NUMERIC_CHECK);
		}
		//获取店铺对应所属区域
		$where['uid'] = $this->postdata['uid'];
		$machineinfo = D('MachineView')->where($where)->select();
		$region = $machineinfo[0]['region'];
		//获取促销分类与详情
		$where1['onsale.time'] = array('gt', intval($this->postdata['saletime']));//下载最新的促销信息
		$where1['onsale.visible'] = 'v';//必须可见
		$where1['onsalecategory.visible'] = 'v';//促销分类也必须可见
		$salelistOld = D('SaleView')->where($where1)->select();
		$salelist = array();
		foreach ($salelistOld as $key => $value) {
			$temp = json_decode($value['ruleregion'], TRUE);
			if(in_array($region, $temp) || count($temp) == 0){
				unset($value['ruleregion']);
				$salelist[] = $value;
			}
		}
		$resp['saleinfo'] = $salelist;
		$rs = json_encode($resp);
		header("Content-Length: ".(strlen($rs)+3));
		//header('Transfer-Encoding:chunked');

		echo $rs;
		exit(0);
	 }
	 
	/**
	 * 检查abstract
	 */
	private function checkabstract(){
		$filename = SYSTEM_ROOT_PATH.'abstract.txt';
		if(!file_exists($filename)){//判断是否存在abstract文件
			touch($filename);
			$newabstract = random_num_str();//10位的abstract
			file_put_contents($filename, $newabstract);
		}
		$abstract = trim(file_get_contents($filename));//系统版本号
		if($abstract !== $this->postdata['abstract']){
			return $abstract;
		}
		return FALSE;
	}
	 
	/**
	 * 撤销订单
	 * 返回Json格式：{status:true/false, code:0/1/2}
	 */
	 public function revokeorder(){
	 	$check = $this->checkdata();
		if($check['status'] === FALSE){//验证错误
			echo json_encode(array('status' => FALSE, 'code' => 0));
			exit(0);
		}
		$where['number'] = $this->postdata['number'];
		$data['type'] = 'withdraw';
		$data['time'] = time();
		$resp = D('Order')->where($where)->save($data);
		if($resp){
			echo json_encode(array('status' => TRUE, 'code' => 1));
			exit(0);
		}else{
			echo json_encode(array('status' => FALSE, 'code' => 2));
			exit(0);
		}
	 }
	 
	/**
	 * 撤销订单
	 * 返回Json格式：{status:true/false, code:0/1/2}
	 */
	 public function revokebatch(){
	 	$check = $this->checkdata();
		if($check['status'] === FALSE){//验证错误
			echo json_encode(array('status' => FALSE, 'code' => 0));
			exit(0);
		}
		$where['number'] = array('in', json_decode($this->postdata['content'], TRUE));
		$data['type'] = 'withdraw';
		$data['time'] = time();
		$resp = D('Order')->where($where)->save($data);
		if($resp){
			echo json_encode(array('status' => TRUE, 'code' => 1));
			exit(0);
		}else{
			echo json_encode(array('status' => FALSE, 'code' => 2));
			exit(0);
		}
	 }
	 
	/**
	 * 提交订单
	 * 
	 */
	 public function order(){
	 	$temp = json_decode($this->postdata['json'], TRUE);
		$orderlist = $temp['order'];
		unset($temp['order']);
		$this->postdata = $temp;
	 	$check = $this->checkdata();
	
		if($check['status'] === FALSE){//验证错误
			echo json_encode(array('status' => FALSE, 'code' => 0));
			exit(0);
		}
		
		$order = D('Order');
		$orderdetail = D('OrderDetail');
		
		//获取uid对应店铺id
		$where['uid'] = $this->postdata['uid'];
		$store = D('Machine')->field('store')->where($where)->find();
		$store = $store['store'];
		
		foreach ($orderlist as $key => $value) {//将订单信息存入数据库
			$temp = array(
				'number'		=> $value['number'],
				'time'			=> intval($value['time']),
				'total'			=> floatval($value['total']),
				'discount'		=> floatval($value['discount']),
				'payment'		=> floatval($value['payment']),
				'store'			=> intval($store),
				'type'			=> ($value['isrevert'] == 0 ? 'normal' : 'withdraw' ),
				'stype'			=> $value['type']
			);
			$order->add($temp);
			$insertId = $order->getLastInsID();
			
			$data = array();
			foreach ($value['orderdetail'] as $dval) {
				$data[] = array(
					'food'			=> $dval['food'],
					'sauce'			=> $dval['sauce'],
					'taste'			=> $dval['taste'],
					'extra'			=> $dval['extra'],
					'order'			=> $insertId,
					'amount'		=> $dval['amount'],
					'total'			=> $dval['total'],
					'discount'		=> $dval['discount'],
					'price'			=> $dval['price'],
					'onsale'		=> $dval['onsale'],
					'saleid'		=> $dval['saleGroupId']
				);
			}
			$orderdetail->addAll($data);
		}
		
		$data = array('updatetime' => strtotime($this->postdata['uptime']));
		$where['uid'] = $this->postdata['uid'];
		D('Machine')->where($where)->save($data);
		
		echo json_encode(array('status' => TRUE, 'code' => 1));
		exit(0);
	 }
}
	